package com.theunderminejournal.updater.gui;

import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import com.theunderminejournal.updater.PropertiesUtil;
import com.theunderminejournal.updater.gui.filter.MarketDataFileFilter;
import com.theunderminejournal.updater.gui.menu.ContextMenuMouseListener;

public class TUJGUI extends JFrame {

	private static final long serialVersionUID = 1L;
	private JPanel jContentPane = null;
	private JButton marketDataFileChooserButton = null;
	private JTextField marketDataFileTextBox = null;
	private JPanel jPanel = null;
	private JTextField tujUrlTextBox = null;
	private JLabel marketDataFileLabel = null;
	private JPanel SingleColumn = null;
	private JPanel tujPanel = null;
	private JLabel tujUrlLabel = null;
	
	private PropertiesUtil properties;  //  @jve:decl-index=0:
	private JButton saveButton = null;
	private JPanel statusPanel = null;  //  @jve:decl-index=0:visual-constraint="453,28"
	private JLabel nextUpdateLabel = null;
	private JLabel nextUpdateTimeLabel = null;
	
	private JLabel lastUpdateLabel = null;
	private JLabel lastUpdateTimeLabel = null;
	
	private DateFormat timeFormat = new SimpleDateFormat("EEE, h:mm a, z");

	
	
	/**
	 * This is the default constructor
	 */
	public TUJGUI() {
		
		super();
		
		properties = new PropertiesUtil();
		
		initialize();
	}

	/**
	 * This method initializes this
	 * 
	 * @return void
	 */
	private void initialize() {
		this.setSize(417, 292);
		this.setContentPane(getJContentPane());
		this.setTitle("TUJ-Updater");
	}

	/**
	 * This method initializes jContentPane
	 * 
	 * @return javax.swing.JPanel
	 */
	private JPanel getJContentPane() {
		if (jContentPane == null) {
			FlowLayout flowLayout = new FlowLayout();
			flowLayout.setHgap(5);
			flowLayout.setAlignment(java.awt.FlowLayout.LEFT);
			jContentPane = new JPanel();
			jContentPane.setLayout(flowLayout);
			jContentPane.add(getSingleColumn(), null);
		}
		return jContentPane;
	}

	/**
	 * This method initializes marketDataFileChooserButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getMarketDataFileChooserButton() {
		if (marketDataFileChooserButton == null) {
			Icon icon = new ImageIcon(getClass().getResource("/javax/swing/plaf/metal/icons/ocean/directory.gif"));
			marketDataFileChooserButton = new JButton(icon);
			marketDataFileChooserButton.addActionListener(new java.awt.event.ActionListener() {
						public void actionPerformed(java.awt.event.ActionEvent e) {
							
							JFileChooser fc = new JFileChooser();
							
							fc.setFileFilter(new MarketDataFileFilter());
							
							int returnVal = fc.showOpenDialog(null);

					        if (returnVal == JFileChooser.APPROVE_OPTION) {
					            File file = fc.getSelectedFile();
					            
					            getMarketDataFileTextBox().setText(file.getAbsolutePath());
					            properties.setMarketDataFile(file.getAbsolutePath());
					        } 
						}
					});
			
			marketDataFileChooserButton.setToolTipText("Examples: C:\\Users\\Public\\Games\\World of Warcraft\\Interface\\AddOns\\TheUndermineJournal\\MarketData.lua");
			
			
		}
		return marketDataFileChooserButton;
	}

	/**
	 * This method initializes marketDataFileTextBox	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getMarketDataFileTextBox() {
		if (marketDataFileTextBox == null) {
			marketDataFileTextBox = new JTextField(30);
			marketDataFileTextBox.setEnabled(false);
			
			
			String marketDataFile = properties.getMarketDataFile();
						
			if(marketDataFile != null){
				marketDataFileTextBox.setText(marketDataFile);
			}else{
				marketDataFileTextBox.setText("Pick you local MarketData.lua file");
			}
			
			marketDataFileTextBox.addMouseListener(new MouseListener() {
				
				public void mouseReleased(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}
				
				public void mousePressed(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}
				
				public void mouseExited(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}
				
				public void mouseEntered(MouseEvent e) {
					// TODO Auto-generated method stub
					
				}
				
				public void mouseClicked(MouseEvent arg0) {
					JFileChooser fc = new JFileChooser();
					
					fc.setFileFilter(new MarketDataFileFilter());
					
					int returnVal = fc.showOpenDialog(null);

			        if (returnVal == JFileChooser.APPROVE_OPTION) {
			            File file = fc.getSelectedFile();
			            
			            getMarketDataFileTextBox().setText(file.getAbsolutePath());
			            properties.setMarketDataFile(file.getAbsolutePath());
			        } 
					
				}
			});
			
			marketDataFileTextBox.setToolTipText("Examples: C:\\Users\\Public\\Games\\World of Warcraft\\Interface\\AddOns\\TheUndermineJournal\\MarketData.lua");
			
		}
		return marketDataFileTextBox;
	}

	/**
	 * This method initializes jPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getJPanel() {
		if (jPanel == null) {
			GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
			gridBagConstraints5.gridx = 0;
			gridBagConstraints5.gridy = 3;
			GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
			gridBagConstraints4.gridx = 1;
			gridBagConstraints4.gridy = 1;
			GridBagConstraints gridBagConstraints2 = new GridBagConstraints();
			gridBagConstraints2.fill = GridBagConstraints.VERTICAL;
			gridBagConstraints2.gridy = 1;
			gridBagConstraints2.weightx = 1.0;
			gridBagConstraints2.anchor = GridBagConstraints.WEST;
			gridBagConstraints2.gridx = 0;
			GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
			gridBagConstraints1.gridx = 0;
			gridBagConstraints1.anchor = GridBagConstraints.WEST;
			gridBagConstraints1.gridy = 0;
			marketDataFileLabel = new JLabel();
			marketDataFileLabel.setText("Market File Location (MarketData.lua)");
			jPanel = new JPanel();
			jPanel.setLayout(new GridBagLayout());
			jPanel.add(getMarketDataFileTextBox(), gridBagConstraints2);
			jPanel.add(marketDataFileLabel, gridBagConstraints1);
			jPanel.add(getMarketDataFileChooserButton(), gridBagConstraints4);
			
			
			
		}
		return jPanel;
	}

	/**
	 * This method initializes tujUrlTextBox	
	 * 	
	 * @return javax.swing.JTextField	
	 */
	private JTextField getTujUrlTextBox() {
		if (tujUrlTextBox == null) {
			tujUrlTextBox = new JTextField(35);
			
			String tujUrl = properties.getTujUrl();
			
			if(tujUrl != null){
				tujUrlTextBox.setText(tujUrl);
			}
			
			//Setup events
			tujUrlTextBox.addKeyListener(new java.awt.event.KeyAdapter() {
				public void keyTyped(java.awt.event.KeyEvent e) {
					saveButton.setEnabled(true);
				}
			});
			
			tujUrlTextBox.addMouseListener(new ContextMenuMouseListener(getSaveButton()));
			
			tujUrlTextBox.setToolTipText("Example: https://theunderminejournal.com/TheUndermineJournal.zip?key=<key>&realms=USA-Gnomeregan");
			
		}
		return tujUrlTextBox;
	}

	private JLabel getTujUrlLabel(){
		if(tujUrlLabel == null){
			tujUrlLabel = new JLabel("TUJ Url");
		}
		
		return tujUrlLabel;
	}
	
	/**
	 * This method initializes SingleColumn	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getSingleColumn() {
		if (SingleColumn == null) {
			GridLayout gridLayout = new GridLayout();
			gridLayout.setRows(4);
			gridLayout.setVgap(8);
			gridLayout.setHgap(0);
			SingleColumn = new JPanel();
			SingleColumn.setLayout(gridLayout);
			
			SingleColumn.add(getJPanel());
			SingleColumn.add(getTujPanel());
			SingleColumn.add(getSaveButton(), null);
			SingleColumn.add(getStatusPanel());
		}
		return SingleColumn;
	}

	/**
	 * This method initializes tujPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getTujPanel() {
		if (tujPanel == null) {
			GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
			gridBagConstraints3.gridx = 0;
			gridBagConstraints3.anchor = GridBagConstraints.WEST;
			gridBagConstraints3.gridy = 0;
			GridBagConstraints gridBagConstraints = new GridBagConstraints();
			gridBagConstraints.fill = GridBagConstraints.VERTICAL;
			gridBagConstraints.gridy = 1;
			gridBagConstraints.weightx = 1.0;
			gridBagConstraints.anchor = GridBagConstraints.WEST;
			gridBagConstraints.gridwidth = 3;
			gridBagConstraints.gridx = 0;
			tujPanel = new JPanel();
			tujPanel.setLayout(new GridBagLayout());
			tujPanel.add(getTujUrlTextBox(), gridBagConstraints);
			tujPanel.add(getTujUrlLabel(), gridBagConstraints3);
			
		}
		return tujPanel;
	}

	/**
	 * This method initializes saveButton	
	 * 	
	 * @return javax.swing.JButton	
	 */
	private JButton getSaveButton() {
		if (saveButton == null) {
			saveButton = new JButton("Save");
			
			saveButton.setEnabled(false);
			
			saveButton.addActionListener(new java.awt.event.ActionListener() {
				public void actionPerformed(java.awt.event.ActionEvent e) {					
					//Validate settings
					  File file = new File(marketDataFileTextBox.getText());
					  if(!file.exists()){
						  //say something						  
						  ErrorDialog dialog = new ErrorDialog(null,true,"MarketFile.lua does not exist.  Please pick a valid MarketData.lua file.");
						  
						  dialog.setAlwaysOnTop(true);
					  }
					  else if( !validUrl(tujUrlTextBox.getText())){
						  ErrorDialog dialog = new ErrorDialog(null,true,"Unable to validate TUJ URL.  Please double check that it is correct.");
						  
						  dialog.setAlwaysOnTop(true);
						  
					  }
					  else{
						  //Set Properties
						  properties.setMarketDataFile(marketDataFileTextBox.getText());
						  properties.setTujUrl(tujUrlTextBox.getText());
						  //Save
						  properties.storeProperties();
						  
						  saveButton.setEnabled(false);
					  }
				}
			});
			
			saveButton.addPropertyChangeListener(new PropertyChangeListener() {
				
				public void propertyChange(PropertyChangeEvent e) {
					// TODO Auto-generated method stub
					if(e.getPropertyName().equals("paste")){
						saveButton.setEnabled(true);
					}
				}
			});
		}
		
		//saveButton.setEnabled(false);
		
		return saveButton;
	}
	
	
	public boolean validUrl(String url){
		//Lets check if the URL contains the correct pattern;
		return url.contains("https://theunderminejournal.com/TheUndermineJournal.zip");
	}

	/**
	 * This method initializes statusPanel	
	 * 	
	 * @return javax.swing.JPanel	
	 */
	private JPanel getStatusPanel() {
		if (statusPanel == null) {
			
			lastUpdateLabel = new JLabel();
			lastUpdateLabel.setText("Last Update Time:");
			
			statusPanel = new JPanel();
			statusPanel.setLayout(new GridLayout(3,2));
			statusPanel.setSize(new Dimension(100, 32));
			
			//Header Row
			statusPanel.add(new JLabel(),0);
			statusPanel.add(new JLabel("Time"),1);
			
			//Last update row
			statusPanel.add(lastUpdateLabel, 2);
			statusPanel.add(getLastUpdateTimeLabel(), 3);
			
			//Next update row
			statusPanel.add(getNextUpdateLabel(), 4);
			statusPanel.add(getNextUpdateTimeLabel(), 5);
			
			
			
			

		}
		return statusPanel;
	}

	/**
	 * This method initializes nextUpdateLabel	
	 * 	
	 * @return javax.swing.JLabel	
	 */
	private JLabel getNextUpdateLabel() {
		if (nextUpdateLabel == null) {
			nextUpdateLabel = new JLabel();
			nextUpdateLabel.setText("Next Update Time:");
		}
		return nextUpdateLabel;
	}
	
	public JLabel getLastUpdateTimeLabel(){
		if(lastUpdateTimeLabel == null){
			lastUpdateTimeLabel = new JLabel();

			if(properties.getLastUpdate() == 0){
				lastUpdateTimeLabel.setText("Never");
			}
			else{
				lastUpdateTimeLabel.setText(timeFormat.format(new Date(properties.getLastUpdate())));				
			}

		}
		
		return lastUpdateTimeLabel;

	}
	
	
	public JLabel getNextUpdateTimeLabel(){
		if(nextUpdateTimeLabel == null){
			nextUpdateTimeLabel = new JLabel();
			
			Long nextUpdate = new Long(properties.getNextUpdate());
			nextUpdateTimeLabel.setText(timeFormat.format(new Date(nextUpdate)));
			
		}
		
		return nextUpdateTimeLabel;
	}
	
}  //  @jve:decl-index=0:visual-constraint="11,13"
